package dbrpc

import (
	"bytes"
	"database/sql"
	"dub/define/grpcmodel"
	"dub/utils"
	"fmt"
	"golang.org/x/net/context"
)

type DbRpcMemLabel struct {
	log *utils.Logger
}

//根据条件查询会员的标签信息
func (m *DbRpcMemLabel) Find(ctx context.Context, args *grpcmodel.ModelDbRpcMemLabelReqFind) (reply *grpcmodel.ModelDbRpcMemLabelResFind, err error) {
	reply = &grpcmodel.ModelDbRpcMemLabelResFind{}
	after_from_buf := bytes.Buffer{}
	params := make([]interface{}, 0)
	after_from_buf.WriteString("from dubmemlabel where memLabelStatus=1")
	for {
		//后面的分页部分
		dbAccounts := NewDbProxy().Get(DB_Accounts)
		if args.GetIsPage() && args.GetPageSize() > 1 {
			sql_str := fmt.Sprintf("select count(memLabelId) %s", after_from_buf.String())
			m.log.Infof("def_func_db_memlabel.go Find method exec %s params is %+v\n", sql_str, params)
			row := dbAccounts.QueryRow(sql_str, params...)
			var total sql.NullInt64
			err := row.Scan(&total)
			if err != nil {
				m.log.Errorf("def_fun_db_memlabel.go Find method dbAccounts.QueryRow err. %v\n", err)
				reply.Err = 2
				break
			}
			if total.Valid {
				if total.Int64 < 1 {
					break
				}
				reply.Total = uint32(total.Int64)
			} else {
				break
			}

			after_from_buf.WriteString(" limit ?,?")
			params = append(params, args.StartRow, args.PageSize)
		}

		sql_str := fmt.Sprintf("select memLabelId,memLabelName %s", after_from_buf.String())
		m.log.Infof("def_func_db_memlabel.go Find method exec %s params is %+v\n", sql_str, params)
		rows, err := dbAccounts.Query(sql_str, params...)
		switch {
		case err == sql.ErrNoRows:
			err = nil
			reply.Err = 1
		case err != nil:
			reply.Err = 2
			m.log.Infof("def_fun_db_memlabel.go Find method dbAccounts.Query err. %v\n", err)
		default:
			reply.Rows = make([]*grpcmodel.ModelDbRpcMemLabel, 0)
			for rows.Next() {
				var (
					memLabelId   sql.NullInt64
					memLabelName sql.NullString
				)
				err := rows.Scan(&memLabelId, &memLabelName)
				if err != nil {
					reply.Err = 2
					m.log.Errorf("def_fun_db_memlabel.go Find method rows.Scan err. %v\n", err)
					break
				}

				tmp_memLabel := grpcmodel.ModelDbRpcMemLabel{}
				if memLabelId.Valid {
					tmp_memLabel.MemLabelId = uint32(memLabelId.Int64)
				}
				if memLabelName.Valid {
					tmp_memLabel.MemLabelName = memLabelName.String
				}
				reply.Rows = append(reply.Rows, &tmp_memLabel)
			}
		}
		break
	}
	return
}

var d_dbRpcMemLabel *DbRpcMemLabel

func NewDbRpcMemLabel() *DbRpcMemLabel {
	if d_dbRpcMemLabel == nil {
		d_dbRpcMemLabel = &DbRpcMemLabel{
			log: utils.NewLogger(),
		}
	}
	return d_dbRpcMemLabel
}
